package com.caszx.chargingpile.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alipay.sdk.app.PayTask;
import com.app.base.app.BaseTopBarDelayActivity;
import com.app.utils.DiskUser;
import com.app.utils.PayResult;
import com.app.utils.SignUtils;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.caszx.chargingpile.wxapi.WXEntryActivity;
import com.rey.material.app.DialogFragment;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;


public class PayActivity extends BaseTopBarDelayActivity implements View.OnClickListener {


    private IWXAPI api;

    private String  ordersId;
    private String  stationName;
    private long  timeLong;
    private String  timeSlot;
    private double  changePower;
    private double  chargeFees;
    private double  serverFees;
    private double  stopFees;
    private double  totalFees;

    private TextView txt_station_name;
    private TextView txt_time;
    private TextView txt_power;
    private TextView txt_price;
    private TextView txt_totalFees;
    private RadioGroup radiogroup_pay;
    private TextView btn_post;

    private static  DecimalFormat decimalFormat = new DecimalFormat("###.##");
    @Override
    protected void init() {
        ordersId = getIntent().getStringExtra("ordersId");
        stationName = getIntent().getStringExtra("stationName");
        timeLong = getIntent().getLongExtra("timeLong",0);
        timeSlot = getIntent().getStringExtra("timeSlot");
        changePower = getIntent().getDoubleExtra("changePower",0);
        chargeFees = getIntent().getDoubleExtra("chargeFees",0);
        serverFees = getIntent().getDoubleExtra("serverFees",0);
        stopFees = getIntent().getDoubleExtra("stopFees",0);
        totalFees = getIntent().getDoubleExtra("totalFees",0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        setCenterTitle("确认支付");
    }

    @Override
    protected void findView() {

        txt_station_name = (TextView) findViewById(R.id.txt_station_name);
        txt_time = (TextView) findViewById(R.id.txt_time);
        txt_power = (TextView) findViewById(R.id.txt_power);
        txt_price = (TextView) findViewById(R.id.txt_price);
        txt_totalFees = (TextView) findViewById(R.id.txt_totalFees);
        radiogroup_pay = (RadioGroup) findViewById(R.id.radiogroup_pay);
        btn_post = (TextView) findViewById(R.id.btn_post);
        btn_post.setOnClickListener(this);

        txt_station_name.setText(stationName);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH 时 mm 分");
        SpannableStringBuilder builderTime = new SpannableStringBuilder();
        builderTime.append("充电时长 ").append(simpleDateFormat.format(new Date(timeLong))).append("\n");
        int start =builderTime.length();
        builderTime.append("充电时间段 ").append(timeSlot==null?"":timeSlot);
        builderTime.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.gray5)),start,builderTime.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        txt_time.setText(builderTime);
        txt_power.setText("充电度数 "+decimalFormat.format(changePower)+"度");

        SpannableStringBuilder builderFee = new SpannableStringBuilder();
        builderFee.append("电费");
        start = builderFee.length();
        builderFee.append("￥").append(decimalFormat.format(chargeFees)).append("\u0020\u0020\u0020\u0020");
        builderFee.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)),start, builderFee.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builderFee.append("服务费");
        start = builderFee.length();
        builderFee.append("￥").append(decimalFormat.format(serverFees)).append("\u0020\u0020\u0020\u0020");;
        builderFee.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)),start, builderFee.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builderFee.append("停车费");
        start = builderFee.length();
        builderFee.append("￥").append(decimalFormat.format(stopFees)).append("\u0020\u0020\u0020\u0020");;
        builderFee.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)),start, builderFee.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        txt_price.setText(builderFee);

        SpannableStringBuilder buildeTotalrFee = new SpannableStringBuilder();
        buildeTotalrFee.append("费用总计  ");
        start = buildeTotalrFee.length();
        buildeTotalrFee.append(totalFees+"");
        builderFee.setSpan(new ForegroundColorSpan(Color.parseColor("#ffFC7802")),start, buildeTotalrFee.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        txt_totalFees.setText(buildeTotalrFee);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.btn_post:

                if(R.id.pay_wallt == radiogroup_pay.getCheckedRadioButtonId()){
                    //支付宝支付
                    payCharge(1);
                }else if(R.id.pay_weixin == radiogroup_pay.getCheckedRadioButtonId()){
                    //微信支付
                    intiWXPay();
                    payCharge(2);
                }else if(R.id.pay_vip == radiogroup_pay.getCheckedRadioButtonId()){
                    DialogHelp.showDialogOnlyMesg(this,"确认支付?", new DialogHelp.DialogActionClickListener() {
                        @Override
                        public void onPositiveActionClicked(DialogFragment fragment) {
                            //会员支付
                            payCharge(3);
                        }

                        @Override
                        public void onNegativeActionClicked(DialogFragment fragment) {
                        }
                    });

                }
                break;
        }
    }




    /***初始化微信支付*/
    private  void intiWXPay(){
        if(api !=null)return;
        api = WXAPIFactory.createWXAPI(this, WXEntryActivity.WEIXIN_APPID);
    }


    private void payWX( JSONObject json){
//        Toast.makeText(this, "launch result = " + api.openWXApp(), Toast.LENGTH_LONG).show();
        try{
                if(null != json  ){
                    PayReq req = new PayReq();
                    req.appId =  WXEntryActivity.WEIXIN_APPID;
//                    req.appId			= json.getString("appid");
                    req.partnerId		= json.getString("partnerid");
                    req.prepayId		= json.getString("prepayid");
                    req.nonceStr		= json.getString("noncestr");
                    req.timeStamp		= json.getString("timestamp");
                    req.packageValue	= json.getString("package");
                    req.sign			= json.getString("sign");
                    req.extData			= "app data"; // optional
                    SnackbarHelp.showSnackbarMsg(this,"正常调起支付...");
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    api.registerApp( WXEntryActivity.WEIXIN_APPID);
                    SnackbarHelp.showSnackbarMsg(this,"拉取微信...");
                    api.sendReq(req);
            }else{
                DialogHelp.showDialogOnlyMesg(this,"服务器请求错误",null);
            }
        }catch(Exception e){
            DialogHelp.showDialogOnlyMesg(this,"异常",null);
        }
    }

    /***
     *
     * @param  patmethod 1、支付宝 2、微信 3、会员卡
     * */
    private void payCharge(final  int patmethod){
        showProgressDialog("获取订单中...");
        HashMap<String,String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this,"token"));
        params.put("patmethod",patmethod+"");
        params.put("ordersId",ordersId);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_PAY_CHARGE)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        // showErrorView(R.string.error_network);
                        //showSnackbarMsg(getString(R.string.error_network));
                         DialogHelp.showDialogOnlyMesg(PayActivity.this,getString(R.string.error_network),null);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject =  response.optJSONObject("result");
                        if(resultJsonObject!=null){
                            int code =  resultJsonObject.optInt("code");
                            if(code<0){
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                //showErrorView(resultJsonObject.optString("msg"));
                                //showSnackbarMsg(resultJsonObject.optString("msg"));
                                 DialogHelp.showDialogOnlyMesg(PayActivity.this,resultJsonObject.optString("msg"),null);
                            }else{
                                try {
                                    if(patmethod == 3){
                                        //会员支付,弹出提示
                                        // DialogHelp.showDialogOnlyMesg(PayActivity.this,resultJsonObject.optString("msg"),null);
                                        finish();
                                    }else if(patmethod == 1){
                                        //支付宝支付
                                        pay(response);
                                    }else if(patmethod == 2){
                                        //微信支付
                                        payWX(response);
                                    }

                                    EventBus.getDefault().post(EventBusAction.ACTION_USER_PAY_SUCCESS);
                                }catch (JSONException e){
                                     DialogHelp.showDialogOnlyMesg(PayActivity.this,getString(R.string.error_parser_json),null);
                                    //showSnackbarMsg(getString(R.string.error_parser_json));
                                    //showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    /**－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－支付开始－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－*/
    /**
     * 生成订单
     *
     * @param productId
     * @param num
     * @param payType
     */
//    private void createOrder(String productId, String num, String payType, JSONObject response) {
//        // 支付宝支付
//        if ("alipay".equals(payType) && Double.parseDouble(response.optString("paymoney"))/100 > 0) {
//            this.pay(response);
//        } else if ("wxpay".equals(payType)) { // 微信支付
//
//        }
//    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                         DialogHelp.showDialogOnlyMesg(PayActivity.this,"支付成功",null);

                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                             DialogHelp.showDialogOnlyMesg(PayActivity.this,"支付结果确认中",null);
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                             DialogHelp.showDialogOnlyMesg(PayActivity.this,"支付失败",null);
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                     DialogHelp.showDialogOnlyMesg( PayActivity.this,"检查结果为：" + msg.obj,null);
                    break;
                }
            }
        };
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     *
     */
    public void pay(JSONObject response) {
        String partnerId = response.optString("partner");
        String private_key = response.optString("private_key");
        String seller = response.optString("seller");
        String ordersId = response.optString("ordersId");
        String title = response.optString("title");
        double totalFees = response.optDouble("totalFees");
        String content = response.optString("content");

        if (TextUtils.isEmpty(partnerId) || TextUtils.isEmpty(private_key)|| TextUtils.isEmpty(seller)) {
            DialogHelp.showDialogTitleMeg(PayActivity.this,"需要配置PARTNER | RSA_PRIVATE| SELLER", "警告", new DialogHelp.DialogActionClickListener() {
                @Override
                public void onPositiveActionClicked(DialogFragment fragment) {
                    finish();
                }
                @Override
                public void onNegativeActionClicked(DialogFragment fragment) {
                }
            });
            return;
        }
        String orderInfo = getOrderInfo(ordersId,partnerId,seller,title, content, totalFees);
        // 对订单做RSA 签名
        String sign = sign(orderInfo, private_key);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"  + getSignType();
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                PayTask alipay = new PayTask(PayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);
                subscriber.onNext(result);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.immediate())
                .subscribe(new Subscriber<String>() {

                    @Override
                    public void onStart() {
                        super.onStart();
                       SnackbarHelp.showSnackbarMsg(PayActivity.this,"调用支付宝");
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(String s) {
                        dissmissProgressDialog();
                        PayResult payResult = new PayResult(s);
                        // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                        String resultInfo = payResult.getResult();

                        String resultStatus = payResult.getResultStatus();

                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
//                          DialogHelp.showDialogOnlyMesg(PayActivity.this,"支付成功",null);
                            EventBus.getDefault().post(EventBusAction.ACTION_USER_PAY_SUCCESS);
                            finish();

                        } else {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000")) {
                                 DialogHelp.showDialogOnlyMesg(PayActivity.this,"支付结果确认中",null);
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                               DialogHelp.showDialogOnlyMesg(PayActivity.this,"支付失败",null);
                            }
                        }
                    }
                });
    }




    /**
     * get the sdk version. 获取SDK版本号
     *
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
    }

    /**
     * create the order info. 创建订单信息
     *
     */
    public String getOrderInfo(String orderId ,String partnerId ,String seller,String subject, String body, double price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + partnerId+ "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + seller + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + orderId + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + ConstantUrl.URL_NOTIFY_PAY + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content
     *            待签名订单信息
     */
    public String sign(String content, String privateKey) {
        return SignUtils.sign(content, privateKey);
    }

    /**
     * get the sign type we use. 获取签名方式
     *
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－支付结束－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－*/

}
